package cn.yuemouren.security.browser.validate.code;

import cn.yuemouren.security.core.validate.code.ValidateCode;
import cn.yuemouren.security.core.validate.code.ValidateCodeRepository;
import cn.yuemouren.security.core.validate.code.ValidateCodeType;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * @Author: Timi
 * @Description: 验证码入session操作类
 * @Date: 2020/7/2 21:16
 * @Version: v1.0
 */
public class SessionValidateCodeRepository implements ValidateCodeRepository {

    /**
     * 验证码放入session时的前缀
     */
    String SESSION_KEY_PREFIX = "SESSION_KEY_FOR_CODE_";

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType type) {
        sessionStrategy.setAttribute(request,getSessionKey(request,type),code);
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType type) {
        return (ValidateCode)sessionStrategy.getAttribute(request,getSessionKey(request,type));
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType type) {
        sessionStrategy.removeAttribute(request,getSessionKey(request,type));
    }

    /**
     * 构建验证码放入session时的key
     *
     * @param request
     * @return
     */
    private String getSessionKey(ServletWebRequest request,ValidateCodeType type) {
        return SESSION_KEY_PREFIX + type.toString().toUpperCase();
    }
}
